#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

BIN=/etc/subweb/subweb.sh
PID=
getPid(){
	local pid=$(ps| grep /etc/subweb/api.py | grep python3 | sed "s/^[ \s]\{1,\}//g;s/[ \s]\{1,\}$//g" | cut -d ' ' -f1)
	PID=$pid
}

start_service() {
	getPid
	local pid=$PID
	if [ ! -z "$pid" ]; then
		echo "Subweb has already run, PID is "$pid
		return 0
	fi
	[ ! -e /etc/subweb/config/subconverter ] && ln -fs /usr/bin/subconverter /etc/subweb/config/subconverter
	local ipInConf=$(cat /etc/subweb/api/aff.py| grep apiip | cut -d "'" -f2 | cut -d ":" -f2 | cut -d "/" -f3)
	local ipOfLan=$(uci get network.lan.ipaddr)
	echo IP in conf is $ipInConf, LAN ip is $ipOfLan
	if [ "$ipOfLan" != "$ipInConf" ]; then
		echo IP mismatch. Change ip in /etc/subweb/api/aff.py
		sed -i 's/'$ipInConf'/'$ipOfLan'/' /etc/subweb/api/aff.py
	fi
	procd_open_instance
	procd_set_param command $BIN
	procd_set_param respawn
	procd_set_param stderr 1
	procd_close_instance
	echo Subweb started.
}

stop_service() {
	getPid
	local pid=$PID
	if [ ! -z "$pid" ]; then
		echo Found subweb process, which PID is $pid
		kill $pid
		echo Subweb process has been terminated.
	else
		echo No subweb process found.
		return 0
	fi
}

reload_service() {
	stop
	start
}
